package com.crm.service.impl;

import com.crm.common.result.AjaxResult;
import com.crm.service.CaptchaService;
import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class CaptchaServiceImpl implements CaptchaService {


    @Autowired
    private Producer captchaProducer;

    @Autowired
    private StringRedisTemplate redisTemplate;

    // 验证码有效期5分钟
    private static final long CAPTCHA_EXPIRE_TIME = 5 * 60;

    /**
     * 生成验证码
     * @return 包含验证码图片和key的对象
     */
    public AjaxResult generateCaptcha() {
        // 生成验证码文本
        String captchaText = captchaProducer.createText();

        // 生成验证码图片
        BufferedImage image = captchaProducer.createImage(captchaText);

        // 转换为Base64字符串
        String base64Image;
        try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
            ImageIO.write(image, "jpg", os);
            base64Image = Base64Utils.encodeToString(os.toByteArray());
        } catch (IOException e) {
            throw new RuntimeException("生成验证码失败", e);
        }

        // 生成UUID作为key
        String uuid = UUID.randomUUID().toString();

        // 存储到Redis，5分钟后过期
        redisTemplate.opsForValue().set(
                "captcha:" + uuid,
                captchaText,
                CAPTCHA_EXPIRE_TIME,
                TimeUnit.SECONDS
        );
        AjaxResult ajax = new AjaxResult();
        ajax.put("uuid", uuid);
        ajax.put("img", base64Image);
        return ajax;
    }

    /**
     * 验证验证码
     * @param key 验证码key
     * @param code 用户输入的验证码
     * @return 是否验证成功
     */
    public boolean validateCaptcha(String key, String code) {
        if (key == null || code == null) {
            return false;
        }

        String redisKey = "captcha:" + key;
        String correctCode = redisTemplate.opsForValue().get(redisKey);

        if (correctCode == null) {
            return false;
        }

        // 验证成功后删除验证码
        redisTemplate.delete(redisKey);

        return correctCode.equalsIgnoreCase(code);
    }
}
